from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

from app.api.api import api_router
from app.core.config import settings
from app.db.base import Base
from app.db.session import engine
from app.services.schedule_service import schedule_service

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="爬虫管理系统",
    description="用于管理和调度爬虫的API",
    version="0.1.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc",
    openapi_url="/api/openapi.json"
)

# 设置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含API路由
app.include_router(api_router, prefix=settings.API_V1_STR)

@app.on_event("startup")
async def startup_event():
    # 初始化所有启用的定时任务
    schedule_service.init_schedules()

@app.get("/")
def read_root():
    return {"message": "欢迎使用爬虫管理系统"}

if __name__ == "__main__":
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)